﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ValidIDCardAttribute.cs
// 功能描述：TongTongMall.MallWeb.Application
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace TongTongMall.MallWeb.Application.Attributes.ModelBinders
{
    /// <summary>
    /// 验证身份证号是否正确
    /// </summary>
    public class ValidIDCardAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var result = new ValidationResult("身份证号不合法！");
            if (value != null && !string.IsNullOrEmpty(value.ToString()))
            {
                var strVal = value.ToString();
                if (strVal.Length == 15 && CheckidnumCardNum15(strVal) && !Regex.IsMatch(strVal, @"^(.)\1{14}$"))
                {
                    result = ValidationResult.Success;
                }
                else if (strVal.Length == 18 && CheckIDCardNum18(strVal) && !Regex.IsMatch(strVal, @"^(.)\1{17}$"))
                {
                    result = ValidationResult.Success;
                }
            }
            else
            {
                result = ValidationResult.Success;
            }
            return result;
        }


        private bool CheckIDCardNum18(string idnum)
        {
            long n = 0;
            if (long.TryParse(idnum.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(idnum.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证
            }
            string province = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (province.IndexOf(idnum.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birthStr = idnum.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime birthDay = new DateTime();
            if (DateTime.TryParse(birthStr, out birthDay) == false)
            {
                return false;//生日验证
            }
            if (birthDay >= DateTime.Now)
            {
                return false;//生日验证
            }
            string[] varifyCodeArr = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] ai = idnum.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (varifyCodeArr[y] != idnum.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }
            return true;//符合GB11643-1999标准
        }
        /// <summary>
        /// 校验是否有效的15位身份证格式
        /// </summary>
        /// <param name="idnum">身份证号</param>
        /// <returns>是否有效</returns>
        private bool CheckidnumCardNum15(string idnum)
        {
            long n = 0;
            if (long.TryParse(idnum, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }
            string province = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (province.IndexOf(idnum.Remove(2)) == -1)
            {
                return false;//省份验证
            }
            string birthStr = idnum.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime birthDay = new DateTime();
            if (DateTime.TryParse(birthStr, out birthDay) == false)
            {
                return false;//生日验证
            }
            if (birthDay >= DateTime.Now)
            {
                return false;//生日验证
            }
            return true;//符合15位身份证标准
        }
    }
}
